package cloud.daodao.storm.dict.helper;

import cloud.daodao.storm.common.model.PageData;
import cloud.daodao.storm.common.model.PageParam;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class JdbcHelper {

    @Resource
    private JdbcClient jdbcClient;

    @SuppressWarnings("SqlSourceToSinkFlow")
    public <P, D> PageData<D> page(PageParam<P> pageParam, List<String> select, String fromWhere, String orderBy, Class<D> clazz) {
        Integer page = pageParam.getPage();
        Integer size = pageParam.getSize();
        int offset = (page - 1) * size;
        P param = pageParam.getParam();

        String limitSql = "limit " + offset + ", " + size;
        String querySql = "select " + String.join(", ", select) + " " + fromWhere + " " + orderBy + " " + limitSql;
        String countSql = "select count(*)" + " " + fromWhere;

        List<D> list = jdbcClient.sql(querySql)
                .paramSource(param)
                .query(clazz)
                .list();
        log.debug("list : {}", list);

        Long total = (Long) jdbcClient.sql(countSql)
                .paramSource(param)
                .query()
                .singleValue();
        log.debug("total : {}", total);

        return new PageData<>(page, size, total, list);
    }

    @SuppressWarnings("SqlSourceToSinkFlow")
    public PageData<Map<String, Object>> page(PageParam<Map<String, Object>> pageParam, List<String> select, String fromWhere, String orderBy) {
        Integer page = pageParam.getPage();
        Integer size = pageParam.getSize();
        int offset = (page - 1) * size;
        Map<String, Object> param = pageParam.getParam();

        String limitSql = "limit " + offset + ", " + size;
        String querySql = "select " + String.join(", ", select) + " " + fromWhere + " " + orderBy + " " + limitSql;
        String countSql = "select count(*)" + " " + fromWhere;

        List<Map<String, Object>> list = jdbcClient.sql(querySql)
                .paramSource(param)
                .query()
                .listOfRows();
        log.debug("list : {}", list);

        Long total = (Long) jdbcClient.sql(countSql)
                .paramSource(param)
                .query()
                .singleValue();
        log.debug("total : {}", total);

        return new PageData<>(page, size, total, list);
    }

}
